package com.banciyuan.bcywebview.biz.main.daily;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.circles.fragment.list.CircleListBaseFragment;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2016/4/29.
 */
public class DailyTagFragment extends CircleListBaseFragment {
    public static final int TYPE_WEEK = 0;
    public static final int TYPE_CATEGORY = 1;
    public static final int TYPE_ALL = 2;
    private DailyTagsAdapter dailyTagsAdapter;
    private PullToRefreshListView mRefreshLv;
    private ListView mListview;
    private ProgressbarHelper mProgressbarHelper;
    private RequestQueue queue;
    private List<TagDetail> tlist = new ArrayList<>();

    private int page = 1;
    private boolean is_load = false;
    private boolean is_end = false;
    private int type;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.circletopic_layout, null);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
        type = getArguments().getInt("type", 0);
    }

    @Override
    protected void initUi(View rootview) {
        mRefreshLv = (PullToRefreshListView) rootview.findViewById(R.id.listView);
        mListview = mRefreshLv.getRefreshableView();

        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dip2px(8, getActivity()));
        View view = new View(getActivity());
        view.setLayoutParams(layoutParams);
        mListview.addHeaderView(view);
    }

    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initData() {
        switch (type) {
            case TYPE_WEEK:
                getWeekTags();
                break;
            case TYPE_CATEGORY:
                getCateGoryTags();
                break;
            case TYPE_ALL:
                getAllTags();
                break;
        }
    }

    @Override
    protected void initAction() {
        mRefreshLv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (type != TYPE_CATEGORY) {
                    if (!is_load && !is_end) {
                        is_load = true;
                        page++;
                        initData();
                    }
                }
            }
        });

        mRefreshLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                is_load = false;
                is_end = false;
                page = 1;
                initData();
            }
        });
    }

    private void getWeekTags() {
        String url = HttpUtils.BASE_URL + TagApi.getWeekTagCircle();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<TagDetail> templist = gson.fromJson(result, new TypeToken<List<TagDetail>>() {
                        }.getType());
                        renderData(templist);
                    } catch (Exception e) {
                        e.printStackTrace();
                        onLoadingFail();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onLoadingFail();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(param);
    }

    private void getCateGoryTags() {
        String url = HttpUtils.BASE_URL + TagApi.getTypeTagCircle();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));

        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray result = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        List<TagDetail> templist = new ArrayList<>();
                        for (int i = 0; i < result.length(); i++) {
                            JSONObject obj = result.getJSONObject(i);
                            String title = obj.getString("type_name");
                            TagDetail tagtitle = new TagDetail();
                            tagtitle.setTitle(title);
                            templist.add(tagtitle);

                            JSONArray data = obj.getJSONArray("tags_data");
                            Gson gson = new Gson();
                            List<TagDetail> subTemplist = gson.fromJson(data.toString(), new TypeToken<List<TagDetail>>() {
                            }.getType());
                            templist.addAll(subTemplist);
                        }
                        renderData(templist);
                    } catch (Exception e) {
                        e.printStackTrace();
                        onLoadingFail();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onLoadingFail();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(param);
    }

    private void onLoadingFail() {
        mProgressbarHelper.onFailed();
        mRefreshLv.onRefreshComplete();
        is_load = false;
    }


    private void getAllTags() {
        String url = HttpUtils.BASE_URL + TagApi.getAllTagCircle();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));

        Map<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<TagDetail> templist = gson.fromJson(result, new TypeToken<List<TagDetail>>() {
                        }.getType());
                        renderData(templist);
                    } catch (Exception e) {
                        e.printStackTrace();
                        onLoadingFail();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onLoadingFail();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(param);
    }

    private void renderData(List<TagDetail> templist) {
        if (page == 1) {
            tlist.clear();
        }
        if (templist.size() == 0) {
            is_end = true;
        }
        tlist.addAll(templist);
        if (dailyTagsAdapter == null) {
            dailyTagsAdapter = new DailyTagsAdapter(tlist, getActivity());
            mListview.setAdapter(dailyTagsAdapter);
            dailyTagsAdapter.setMlistView(mListview);
        } else {
            dailyTagsAdapter.notifyDataSetChanged();
        }
        mRefreshLv.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        is_load = false;
    }
}
